package com.crm.interceptor;


import org.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.crm.entity.User;
import com.crm.util.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @data 2020/4/4 14:38
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        response.setCharacterEncoding("utf-8");
        String tokenStr = request.getHeader("token");

        if (tokenStr != null && tokenStr != "") {
            try {
                User admin = TokenUtil.unsign(tokenStr, User.class);
                if (admin != null) {
                    return true;
                }
            } catch (Exception e) {

            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        json.put("success", "false");
        json.put("msg", "认证失败");
        json.put("code", "500");
        response.getWriter().append(json.toString());
        System.out.println("认证失败");
        return false;
    }
}

